package com.store.app.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.RecordListAdapter;
import com.store.app.bean.EventBusBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.StringUtils;
import com.store.app.utils.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import de.greenrobot.event.EventBus;


/**
 * 账户页面
 */
public class AccountCheckingActivity extends BaseActivity implements OnScrollListener, View.OnClickListener, IOnHttpListener {

    /**标题栏--标题*/
    private TextView tvTitle;

    /**零钱余额容器*/
    private LinearLayout cash_records;
    /**佣金条目容器*/
    private LinearLayout ll_commission;
    /**金币余额容器*/
    private LinearLayout gold_records;
    /**礼券余额容器*/
    private LinearLayout certificate_records;

    /**零钱余额*/
    private TextView balance;
    /**佣金数额*/
    private TextView tv_commission;
    /**金币余额*/
    private TextView gold;
    /**礼券余额*/
    private TextView wallet;

    /**收银记录容器*/
    private LinearLayout llRecord;
    /**显示日期*/
    private TextView setdate_tv;
    /**选择日期*/
    private TextView checkdate_tv;

    /**收银记录--现金*/
    private TextView in_case_sum;
    /**收银记录--收入*/
    private TextView in_sum;
    /**收银记录--单数*/
    private TextView num_count;

    /**数据加载中条目*/
    private LinearLayout cache;
    /**收音记录信息列表*/
    private ListView listrecord;
    /**listrecord的脚布局--一直隐藏*/
    private View moreView;

    private Context context;
    private NetRequest netRequest;

    private boolean iscashiser = false;

    private int lastItem;
    private int count;
    private JSONArray datarecords = new JSONArray();

    private String today_date = "", set_date = "";

    private RecordListAdapter recordlist;

    private String cash_froze = "";         // 零钱--冻结
    private String credit_balance = "";     // 零钱--授信

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ExitApplication.getInstance().addActivity(this);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        EventBus.getDefault().register(this);

        iscashiser = getIntent().getBooleanExtra("iscashiser", false);
        setContentView(R.layout.wallet);

        context = AccountCheckingActivity.this;

        llRecord = (LinearLayout) findViewById(R.id.ll_caish_record);

        moreView = getLayoutInflater().inflate(R.layout.load, null);

        listrecord = (ListView) findViewById(R.id.listrecord);
        recordlist = new RecordListAdapter(context, datarecords);
        listrecord.addFooterView(moreView);
        listrecord.setAdapter(recordlist);
        listrecord.setOnScrollListener(this);

        cache = (LinearLayout) findViewById(R.id.cache);

        //零钱余额
        balance = (TextView) findViewById(R.id.balance);
        balance.setText(MoneyUtil.addComma(Stores.cash_balance + ""));
        //佣金余额
        tv_commission = (TextView) findViewById(R.id.tv_commission);
        tv_commission.setText(MoneyUtil.addComma(Stores.total_cash_commission + ""));
        //金币余额
        gold = (TextView) findViewById(R.id.gold);
        gold.setText(MoneyUtil.addComma(Stores.gold + ""));
        //礼券余额
        wallet = (TextView) findViewById(R.id.wallet);
        wallet.setText(MoneyUtil.addComma((int) Stores.voucher_balance + ""));

        in_case_sum = (TextView) findViewById(R.id.in_case_sum);
        in_sum = (TextView) findViewById(R.id.in_sum);
        num_count = (TextView) findViewById(R.id.num_count);

        //零钱余额容器
        cash_records = (LinearLayout) findViewById(R.id.cash_records);
        //佣金余额容器
        ll_commission = (LinearLayout) findViewById(R.id.ll_commission);
        //金币余额容器
        gold_records = (LinearLayout) findViewById(R.id.gold_records);
        //礼券余额容器
        certificate_records = (LinearLayout) findViewById(R.id.certificate_records);

        //日期设置
        setdate_tv = (TextView) findViewById(R.id.wallet_tv_date);
        checkdate_tv = (TextView) findViewById(R.id.wallet_btn_date);
        checkdate_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示日期选择器
                showDatePicker();
            }
        });
        Long tsLong = System.currentTimeMillis() / 1000;
        today_date = time_sign(tsLong);
        set_date = today_date;
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void onEvent(EventBusBean eventBusBean) {
        if (eventBusBean.type == 222) {
            Log.v("zyl", "onEvent 收到广播去刷新余额");
            netRequest.requestQueryAccount(1);
        }
    }

    private void initView() {
        netRequest = new NetRequest(this);
        netRequest.requestQueryAccount(1);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        if (iscashiser) {
            tvTitle.setText("收银记录");
            cash_records.setVisibility(View.GONE);
            certificate_records.setVisibility(View.GONE);
            gold_records.setVisibility(View.GONE);
            ll_commission.setVisibility(View.GONE);
            ImageView img_line = (ImageView) findViewById(R.id.top_line);//收银记录与礼券之间的分割线
            img_line.setVisibility(View.GONE);
            TextView textView = (TextView) findViewById(R.id.tv_syjl);//收银记录
//            textView.setVisibility(View.INVISIBLE);
            llRecord.setVisibility(View.VISIBLE);
        } else {
            TextView textView = (TextView) findViewById(R.id.tv_syjl);//收银记录
            textView.setText("收银记录");
            llRecord.setVisibility(View.VISIBLE);
            tvTitle.setText("账户");
            //零钱余额容器
            cash_records.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(AccountCheckingActivity.this, MoneyBalanceActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    intent.putExtra("cash_froze", MoneyUtil.formatMoney(cash_froze));
                    intent.putExtra("credit_balance", MoneyUtil.formatMoney(credit_balance));
                    startActivity(intent);
                }
            });

            //佣金余额容器
            ll_commission.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CommissionBalanceActivity.show(AccountCheckingActivity.this, Stores.cash_balance);
                }
            });

            //金币余额容器
            gold_records.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(AccountCheckingActivity.this, GoldBalanceActivity.class));
                }
            });

            //礼券余额容器
            certificate_records.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(AccountCheckingActivity.this, CouponBalanceActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(intent);
                }
            });
        }

        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void showDatePicker() {
        Calendar mycalendar = Calendar.getInstance(Locale.getDefault());
        int year = mycalendar.get(Calendar.YEAR);
        int month = mycalendar.get(Calendar.MONTH);
        int day = mycalendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dpd = new DatePickerDialog(AccountCheckingActivity.this,datelistener, year, month, day);
        //设置日期是否可编辑 点击是否弹出软键盘 AlertDialog.THEME_TRADITIONAL AlertDialog.THEME_HOLO_DARK AlertDialog.THEME_HOLO_LIGHT
        dpd.getDatePicker().setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
        dpd.getDatePicker().setMaxDate(new Date().getTime());
        dpd.show();//显示DatePickerDialog组件
    }

    private DatePickerDialog.OnDateSetListener datelistener = new DatePickerDialog.OnDateSetListener() {
        /**params：view：该事件关联的组件
         * params：myyear：当前选择的年
         * params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            //更新日期
            Calendar mycalendar = Calendar.getInstance();
            mycalendar.set(Calendar.YEAR, myyear);
            mycalendar.set(Calendar.MONTH, monthOfYear);
            mycalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            set_date = Utils.getTime(mycalendar);
            if (today_date.equals(set_date)) {
                setdate_tv.setText("今天");
            } else {
                setdate_tv.setText(set_date);
            }
            netRequest.requestTradeStatistic(2, set_date);
            netRequest.requestTakeRecords(3, set_date);
        }
    };

    @Override
    public void onResume() {
        //查询交易统计
        netRequest.requestTradeStatistic(2, today_date);
        netRequest.requestTakeRecords(3, today_date);
        netRequest.requestQueryAccount(1);
        super.onResume();
    }

    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        lastItem = firstVisibleItem + visibleItemCount - 1; // 减1是因为上面加了个addFooterView
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // 下拉到空闲是，且最后一个item的数等于数据的总数时，进行更新
        if (lastItem == count
                && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //查询账户信息
        if (requestId == 1) {
            try {
                JSONObject jsonObject = new JSONObject(result);

                double cashBalance = Double.parseDouble(jsonObject.optString("cash_balance"));  //零钱
                cash_froze = jsonObject.optString("cash_froze");                                //零钱--冻结
                credit_balance = jsonObject.optString("credit_balance");                        //零钱--授信

                String strTotalAmount = jsonObject.optString("totalAmount");                    // 总佣金
                if (StringUtils.isEmptyOrNull(strTotalAmount)) strTotalAmount = "0.00";
                Stores.total_cash_commission = Double.parseDouble(strTotalAmount);

                int vo = Integer.parseInt(jsonObject.optString("voucher_balance"));             //礼券
                Stores.cash_balance = cashBalance;
                Stores.gold = jsonObject.optString("gold");                                     //金币
                Stores.voucher_balance = vo;

                balance.setText(MoneyUtil.addComma(Stores.cash_balance + ""));
                tv_commission.setText(MoneyUtil.addComma(Stores.total_cash_commission + ""));
                gold.setText(MoneyUtil.addComma(Stores.gold + ""));
                wallet.setText(MoneyUtil.addComma((int) Stores.voucher_balance + ""));

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 2) {//查询交易统计记录
            try {
                JSONObject jsonObject = new JSONObject(result);
                in_case_sum.setText(jsonObject.get("in_case_sum") + "");
                in_sum.setText(jsonObject.get("in_sum") + "");
                num_count.setText(jsonObject.get("num_count") + "");
            } catch (Exception e) {
            }
        } else if (requestId == 3) {//查询收银记录
            try {
                JSONArray jsonArray = new JSONArray(result);
                count = recordlist.getCount();
                cache.setVisibility(View.GONE);
                moreView.setVisibility(View.GONE);
                recordlist = new RecordListAdapter(context, jsonArray);
                listrecord.setAdapter(recordlist);
                Utils.Setlistview(listrecord);
            } catch (Exception e) {
            }
        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.v("zyl", "onExecuteFail:" + msg);
        showToast(msg);
    }


    public String time_sign(long first_time) {
        Date date = new Date(first_time * 1000);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return dateString;
    }

}